﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Example.Base.Interfaces.Services.DataServices;
using System.Xml.Linq;
using RestSharp;
using System.Threading;
using Example.Base.Entities;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Site.Test")]
namespace Example.Data.Services.DataServices
{
    public class TwitterService : IDataService<IEnumerable<Tweet>>
    {
        public Task<IEnumerable<Tweet>> AsyncGet()
        {
            throw new NotImplementedException();
        }
    }    
    public static class TwitterServiceExtension
    {
        internal static Func<IDataService<IEnumerable<Tweet>>, string, Task<IEnumerable<Tweet>>> AsyncGetFactory = 
            (dataService, query) => Task.Factory.StartNew<IEnumerable<Tweet>>(() => { 
                return privateAsyncGet(dataService, query); 
            });

        #region Get Twitts
        public static Task<IEnumerable<Tweet>> AsyncGet(this IDataService<IEnumerable<Tweet>> dataService, string q)
        {
            return AsyncGetFactory(dataService, q);
        }

        private static IEnumerable<Tweet> privateAsyncGet(IDataService<IEnumerable<Tweet>> dataService, string query)
        {
            var client = new RestClient();
            client.BaseUrl = "http://search.twitter.com";

            var request = new RestRequest();
            request.Resource = "search.json";
            request.AddParameter("q", query);

            var response = client.Execute(request);

            if (!String.IsNullOrEmpty(response.Content))
            {

                JToken obj = JObject.Parse(response.Content);

                var t = obj.SelectToken("results");

                var tweets = t.Select(x => new Tweet
                    {
                        UserName = x["from_user"].ToString(),
                        Text = x["text"].ToString(),
                    });

                return tweets;
            }
            else
            {
                return new List<Tweet>();
            }
        }
        #endregion
    }
}
